package com.project.smms.controller;

import com.project.smms.pojo.Goods;
import com.project.smms.pojo.Order;
import com.project.smms.service.GoodsService;
import com.project.smms.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;
import java.util.List;

/**
 * @author 莫息涛
 * @Description: 商品的控制层
 * @date 2020/3/7 15:11
 */
@Controller
public class GoodsController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/selectGoods")
    public String selectGoods(Model model){
        Collection<Goods> goods = goodsService.selectGoods();
        model.addAttribute("goods",goods);
        return "goods";
    }

    @RequestMapping("/deleteGoods/{goods_id}")
    public String deleteGoods(@PathVariable("goods_id") Integer id, Model model){
        try {
            goodsService.deleteGoods(id);
        }catch (Exception e){
            return "errordata";
        }finally {
            Collection<Goods> goods = goodsService.selectGoods();
            model.addAttribute("goods",goods);
        }
        return "goods";
    }

    @RequestMapping("/toAddGoodsPage")
    public String toAddPage(Model model){
        List<Order> order = orderService.selectOrder();
        model.addAttribute("ordergoods",order);
        return "addgoods";
    }

    @RequestMapping("/addGoods")
    public String addGoods(Goods goods, Model model){
        try {
            goodsService.addGoods(goods);
        }catch (Exception e){
            return "errordata";
        }finally {
            Collection<Goods> goods1 = goodsService.selectGoods();
            model.addAttribute("goods",goods1);
        }
        return "goods";
    }

    @RequestMapping("/toUpdateGoodsPage/{goods_id}")
    public String toUpdatePage(@PathVariable("goods_id") Integer id,Model model){
        List<Order> order = orderService.selectOrder();
        Goods goods = goodsService.selectGoodsById(id);
        model.addAttribute("ordergoods",order);
        model.addAttribute("updategoods",goods);
        return "updategoods";
    }

    @RequestMapping("/updateGoods")
    public String updateGoods(Goods goods, Model model){
        try {
            goodsService.updateGoods(goods);
        }catch (Exception e){
            return "errordata";
        }finally {
            Collection<Goods> goods1 = goodsService.selectGoods();
            model.addAttribute("goods",goods1);
        }
        return "goods";
    }
}
